import React, { useEffect, useState, useRef } from 'react';
import { http, API_PATH } from '../utils/http';

interface MaterialDetail {
    id: string;
    url: string;
    title: string;
    source: string;
    author: string;
    read_count: string;
    tags: string[];
    status: string;
    error: string | null;
    content: string;
    content_length: number;
    created_at: number;
    processed_at: number;
    processing_time: number;
    topic_extracted: boolean;
    user_id?: string;
    display_name?: string;
}

const MaterialDetail: React.FC = () => {
    // 获取素材ID
    const id = window.location.pathname.split('/').pop() || '';

    // 素材详情数据
    const [material, setMaterial] = useState<MaterialDetail | null>(null);
    // 加载状态
    const [loading, setLoading] = useState(true);
    // 错误信息
    const [error, setError] = useState<string | null>(null);
    // 复制成功提示
    const [copySuccess, setCopySuccess] = useState(false);
    // 提取话题状态
    const [extracting, setExtracting] = useState(false);
    // 提示消息
    const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' | 'info'; visible: boolean }>({
        message: '',
        type: 'info',
        visible: false
    });
    // 编辑模式
    const [isEditing, setIsEditing] = useState(false);
    // 编辑内容
    const [editContent, setEditContent] = useState('');
    // 保存确认弹窗
    const [showSaveConfirm, setShowSaveConfirm] = useState(false);
    // 保存状态
    const [saving, setSaving] = useState(false);
    // 提取话题确认弹窗
    const [showExtractConfirm, setShowExtractConfirm] = useState(false);
    // 是否为HTML编辑模式
    const [isHtmlMode, setIsHtmlMode] = useState(true);

    // textarea引用
    const textareaRef = useRef<HTMLTextAreaElement>(null);
    // 富文本编辑器引用
    const richEditorRef = useRef<HTMLDivElement>(null);

    // 自动调整文本区域高度
    const autoResizeTextarea = () => {
        const textarea = textareaRef.current;
        if (textarea) {
            textarea.style.height = 'auto';
            textarea.style.height = textarea.scrollHeight + 'px';
        }
    };

    // 显示Toast提示
    const showToast = (message: string, type: 'success' | 'error' | 'info' = 'info') => {
        setToast({ message, type, visible: true });
        setTimeout(() => {
            setToast(prev => ({ ...prev, visible: false }));
        }, 2000);
    };

    // 格式化HTML代码
    const formatHtml = (html: string): string => {
        if (!html) return '';

        try {
            // 创建临时DOM元素
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = html.trim();

            // 递归格式化HTML
            const formatNode = (node: Node, level: number = 0): string => {
                // 文本节点直接返回内容
                if (node.nodeType === Node.TEXT_NODE) {
                    const text = node.textContent?.trim() || '';
                    return text ? '  '.repeat(level) + text + '\n' : '';
                }

                // 元素节点
                if (node.nodeType === Node.ELEMENT_NODE) {
                    const element = node as Element;
                    const tagName = element.tagName.toLowerCase();
                    const indent = '  '.repeat(level);

                    // 获取属性
                    const attributes = Array.from(element.attributes)
                        .map(attr => `${attr.name}="${attr.value}"`)
                        .join(' ');

                    // 没有子节点的情况
                    if (!element.firstChild) {
                        return `${indent}<${tagName}${attributes ? ' ' + attributes : ''}></${tagName}>\n`;
                    }

                    // 只有文本内容的简单元素
                    if (element.childNodes.length === 1 && element.firstChild?.nodeType === Node.TEXT_NODE && element.firstChild.textContent?.trim()) {
                        return `${indent}<${tagName}${attributes ? ' ' + attributes : ''}>${element.firstChild.textContent}</${tagName}>\n`;
                    }

                    // 有子元素的复杂元素
                    let result = `${indent}<${tagName}${attributes ? ' ' + attributes : ''}>\n`;
                    element.childNodes.forEach(child => {
                        result += formatNode(child, level + 1);
                    });
                    result += `${indent}</${tagName}>\n`;
                    return result;
                }

                return '';
            };

            let formatted = '';
            tempDiv.childNodes.forEach(node => {
                formatted += formatNode(node);
            });

            return formatted;
        } catch (error) {
            console.error('格式化HTML时出错:', error);
            return html;
        }
    };

    // 切换编辑模式
    const handleToggleEdit = () => {
        if (isEditing) {
            // 退出编辑模式
            setIsEditing(false);
        } else {
            // 进入编辑模式，设置格式化后的初始内容
            setEditContent(material?.content ? formatHtml(material.content) : '');
            setIsEditing(true);
            // 默认进入HTML编辑模式
            setIsHtmlMode(true);
        }
    };

    // 切换HTML/富文本编辑模式
    const toggleEditMode = () => {
        if (isHtmlMode) {
            // 从HTML模式切换到富文本模式
            if (richEditorRef.current) {
                richEditorRef.current.innerHTML = editContent;
            }
        } else {
            // 从富文本模式切换到HTML模式
            if (richEditorRef.current) {
                setEditContent(formatHtml(richEditorRef.current.innerHTML));
            }
        }
        setIsHtmlMode(!isHtmlMode);
    };

    // 富文本编辑器内容变更
    const handleRichEditorChange = () => {
        if (richEditorRef.current) {
            // 不需要格式化，因为这里我们只是临时保存内容
            // 我们不直接设置editContent，因为会导致格式化，影响编辑体验
            // 只在需要保存或切换到HTML模式时才更新
        }
    };

    // 内容变更处理
    const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
        setEditContent(e.target.value);
        // 自动调整高度
        setTimeout(autoResizeTextarea, 0);
    };

    // 在内容设置后自动调整高度
    useEffect(() => {
        if (isEditing) {
            autoResizeTextarea();
        }
    }, [isEditing, editContent]);

    // 处理保存内容
    const handleSaveContent = async () => {
        if (!material?.id) return;
        setShowSaveConfirm(false);
        setSaving(true);

        try {
            const response = await http.post<{
                material_id: string;
                updated: boolean;
                title: string;
                content_length: number;
            }>('/v1/material/update-content', {
                material_id: material.id,
                content: editContent
            });

            response.onSuccess(() => {
                showToast('内容保存成功', 'success');
                // 更新本地数据
                if (response.data) {
                    const updatedData = response.data;
                    setMaterial(prev => {
                        if (!prev) return null;
                        return {
                            ...prev,
                            content: editContent,
                            content_length: updatedData.content_length,
                            title: updatedData.title
                        };
                    });
                }
                // 退出编辑模式
                setIsEditing(false);
            }).onError((code, msg) => {
                console.error(`保存内容失败: 错误码 ${code}, 消息: ${msg}`);
                showToast(`保存内容失败: ${msg}`, 'error');
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            showToast('网络请求异常', 'error');
        } finally {
            setSaving(false);
        }
    };

    // 点击保存按钮
    const handleClickSave = () => {
        setShowSaveConfirm(true);
    };

    // 提取话题
    const handleExtractTopic = async () => {
        if (!material?.id) return;

        // 如果已经提取过，显示确认弹窗
        if (material.topic_extracted) {
            setShowExtractConfirm(true);
            return;
        }

        await doExtractTopic();
    };

    // 执行提取话题
    const doExtractTopic = async () => {
        if (!material?.id) return;

        setExtracting(true);
        try {
            const response = await http.post<{
                material_id: string;
                topic: string;
                job_id: string;
                articles_count: number;
            }>('/v1/material/extract-topic', {
                material_id: material.id
            });

            response.onSuccess(() => {
                showToast('话题提取任务已提交', 'success');
                // 更新本地状态
                setMaterial(prev => {
                    if (!prev) return null;
                    return {
                        ...prev,
                        topic_extracted: true
                    };
                });
            }).onError((code, msg) => {
                console.error(`提取话题失败: 错误码 ${code}, 消息: ${msg}`);
                showToast(`提取话题失败: ${msg}`, 'error');
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            showToast('网络请求异常', 'error');
        } finally {
            setExtracting(false);
            setShowExtractConfirm(false);
        }
    };

    // 复制内容
    const handleCopy = async () => {
        if (!material?.content) return;

        try {
            await navigator.clipboard.writeText(material.content);
            setCopySuccess(true);
            setTimeout(() => setCopySuccess(false), 2000);
        } catch (err) {
            console.error('复制失败:', err);
            setError('复制失败，请重试');
        }
    };

    // 获取素材详情
    const fetchMaterialDetail = async () => {
        try {
            const response = await http.get<MaterialDetail>(`${API_PATH.MATERIAL.DETAIL}/${id}`);

            response.onSuccess(() => {
                if (response.data) {
                    setMaterial(response.data);
                } else {
                    setError('获取素材详情失败');
                }
            }).onError((code, msg) => {
                console.error(`获取素材详情失败: 错误码 ${code}, 消息: ${msg}`);
                setError(`获取素材详情失败: ${msg}`);
            });
        } catch (error) {
            console.error('网络请求异常:', error);
            setError('网络请求异常');
        } finally {
            setLoading(false);
        }
    };

    // 页面加载时获取数据
    useEffect(() => {
        fetchMaterialDetail();
    }, [id]);

    // 返回素材中心
    const handleBack = () => {
        window.location.href = '/material-center';
    };

    // 格式化时间
    const formatDate = (timestamp: number) => {
        const date = new Date(timestamp);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        });
    };

    // 格式化处理时间
    const formatProcessingTime = (ms: number) => {
        const seconds = Math.floor(ms / 1000);
        if (seconds < 60) {
            return `${seconds}秒`;
        }
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        return `${minutes}分${remainingSeconds}秒`;
    };

    // 处理图片路径，将相对路径转为绝对路径
    const processImageUrls = (html: string): string => {
        if (!material?.url) return html;

        try {
            // 创建一个基础URL，用于转换相对路径
            const baseUrl = new URL(material.url);
            const origin = baseUrl.origin;
            const basePath = baseUrl.pathname.split('/').slice(0, -1).join('/');

            // 创建临时DOM元素来处理HTML
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = html;

            // 处理所有图片元素
            const imgElements = tempDiv.querySelectorAll('img');
            imgElements.forEach(img => {
                if (img.src) {
                    try {
                        // 尝试创建URL对象，判断是否是绝对URL
                        new URL(img.src);
                    } catch {
                        // 如果不是有效的绝对URL，则转换为绝对URL
                        if (img.src.startsWith('/')) {
                            // 以根路径开头
                            img.src = `${origin}${img.src}`;
                        } else {
                            // 相对路径
                            img.src = `${origin}${basePath}/${img.src}`;
                        }
                    }

                    // 添加加载错误处理
                    img.setAttribute('onerror', "this.onerror=null; this.classList.add('img-load-error');");
                }
            });

            return tempDiv.innerHTML;
        } catch (error) {
            console.error('处理图片URL时出错:', error);
            return html;
        }
    };

    return (
        <div className="min-h-screen bg-gray-50">
            {/* 顶部导航栏 */}
            <header className="bg-white border-b border-gray-200 shadow-sm sticky top-0 z-10">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="flex justify-between items-center h-16">
                        <div className="flex items-center">
                            <button
                                onClick={handleBack}
                                className="inline-flex items-center px-3 py-2 border border-gray-200 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
                            >
                                <svg className="w-5 h-5 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                                </svg>
                                返回素材中心
                            </button>
                        </div>
                        <h1 className="text-xl font-semibold text-gray-900">素材详情</h1>
                    </div>
                </div>
            </header>

            {/* 主内容区 */}
            <main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                {loading ? (
                    <div className="flex justify-center items-center py-16">
                        <div className="flex flex-col items-center">
                            <svg className="animate-spin h-10 w-10 text-indigo-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                            <span className="mt-3 text-gray-600 font-medium">加载中...</span>
                        </div>
                    </div>
                ) : error ? (
                    <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-8 text-center">
                        <div className="flex flex-col items-center">
                            <svg className="w-16 h-16 text-rose-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                            <h3 className="mt-4 text-lg font-medium text-gray-900">加载失败</h3>
                            <p className="mt-1 text-gray-500">{error}</p>
                            <button
                                onClick={fetchMaterialDetail}
                                className="mt-6 inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                            >
                                <svg className="-ml-1 mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                                </svg>
                                重试
                            </button>
                        </div>
                    </div>
                ) : material ? (
                    <div className="space-y-8">
                        {/* 文章信息卡片 */}
                        <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                            <div className="p-6">
                                <div className="flex items-start justify-between">
                                    <div className="flex-1">
                                        <div className="flex items-center gap-3 mb-4">
                                            <span className={`inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium ${material.status === 'completed' ? 'bg-emerald-50 text-emerald-600 border border-emerald-200' :
                                                material.status === 'processing' ? 'bg-sky-50 text-sky-600 border border-sky-200' :
                                                    material.status === 'failed' ? 'bg-rose-50 text-rose-600 border border-rose-200' :
                                                        'bg-indigo-50 text-indigo-600 border border-indigo-200'
                                                }`}>
                                                {material.status === 'completed' ? '已完成' :
                                                    material.status === 'processing' ? '处理中' :
                                                        material.status === 'failed' ? '处理失败' : '待处理'}
                                            </span>
                                            <span className="text-sm text-gray-500">ID: {material.id}</span>
                                            <button
                                                onClick={handleExtractTopic}
                                                disabled={extracting}
                                                className={`inline-flex items-center px-2.5 py-1 rounded-md text-xs font-medium ${extracting
                                                    ? 'bg-gray-50 text-gray-400 border border-gray-200 cursor-not-allowed'
                                                    : material.topic_extracted
                                                        ? 'bg-emerald-50 text-emerald-600 border border-emerald-200 hover:bg-emerald-100'
                                                        : 'bg-indigo-50 text-indigo-600 border border-indigo-200 hover:bg-indigo-100'
                                                    }`}
                                            >
                                                <svg className={`w-3.5 h-3.5 mr-1 ${extracting ? 'animate-spin' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                                                </svg>
                                                {extracting ? '提取中...' : material.topic_extracted ? '重新提取话题' : '提取话题'}
                                            </button>
                                        </div>

                                        <h1 className="text-2xl font-bold text-gray-900 mb-4">
                                            {material.title}
                                        </h1>

                                        <div className="flex items-center gap-6 text-sm text-gray-500 mb-4">
                                            <span className="flex items-center">
                                                <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9.5a2 2 0 00-2-2h-2" />
                                                </svg>
                                                {material.source}
                                            </span>
                                            <span className="flex items-center">
                                                <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                                </svg>
                                                {material.author}
                                            </span>
                                            {material.display_name && (
                                                <span className="flex items-center">
                                                    <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
                                                    </svg>
                                                    上传者：{material.display_name}
                                                </span>
                                            )}
                                        </div>

                                        <div className="flex flex-wrap gap-2 mb-4">
                                            {material.tags?.map((tag, index) => (
                                                <span
                                                    key={index}
                                                    className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800"
                                                >
                                                    {tag}
                                                </span>
                                            ))}
                                        </div>

                                        <div className="flex items-center justify-between text-sm text-gray-500">
                                            <div className="flex items-center gap-4">
                                                <span>创建时间：{formatDate(material.created_at)}</span>
                                                {material.processed_at && (
                                                    <span>处理时间：{formatDate(material.processed_at)}</span>
                                                )}
                                                {material.processing_time && (
                                                    <span>处理耗时：{formatProcessingTime(material.processing_time)}</span>
                                                )}
                                            </div>
                                            <a
                                                href={material.url}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="inline-flex items-center text-emerald-600 hover:text-emerald-700"
                                            >
                                                <span>阅读原文</span>
                                                <svg className="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                                                </svg>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* 文章内容卡片 */}
                        <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                            <div className="p-6">
                                <div className="flex items-center justify-between mb-4">
                                    <h2 className="text-lg font-medium text-gray-900">文章内容</h2>
                                    <div className="flex items-center gap-4">
                                        <span className="text-sm text-gray-500">
                                            字数：{material.content_length}
                                        </span>
                                        {isEditing ? (
                                            <div className="flex items-center gap-2">
                                                <button
                                                    onClick={toggleEditMode}
                                                    className="inline-flex items-center px-3 py-1.5 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
                                                >
                                                    {isHtmlMode ? (
                                                        <>
                                                            <svg className="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M7 21h10a2 2 0 002-2V9l-6-6H9a2 2 0 00-2 2v14a2 2 0 002 2z" />
                                                            </svg>
                                                            切换到富文本编辑
                                                        </>
                                                    ) : (
                                                        <>
                                                            <svg className="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" />
                                                            </svg>
                                                            切换到HTML编辑
                                                        </>
                                                    )}
                                                </button>
                                                <button
                                                    onClick={handleClickSave}
                                                    disabled={saving}
                                                    className="inline-flex items-center px-3 py-1.5 border border-emerald-500 rounded-lg text-sm font-medium text-white bg-emerald-600 hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-emerald-500 transition-colors"
                                                >
                                                    {saving ? (
                                                        <>
                                                            <svg className="animate-spin w-4 h-4 mr-1.5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                                            </svg>
                                                            保存中...
                                                        </>
                                                    ) : (
                                                        <>
                                                            <svg className="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7" />
                                                            </svg>
                                                            保存内容
                                                        </>
                                                    )}
                                                </button>
                                                <button
                                                    onClick={handleToggleEdit}
                                                    className="inline-flex items-center px-3 py-1.5 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
                                                >
                                                    <svg className="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                                                    </svg>
                                                    取消
                                                </button>
                                            </div>
                                        ) : (
                                            <div className="flex items-center gap-2">
                                                <button
                                                    onClick={handleToggleEdit}
                                                    className="inline-flex items-center px-3 py-1.5 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
                                                >
                                                    <svg className="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />
                                                    </svg>
                                                    编辑内容
                                                </button>
                                                <button
                                                    onClick={handleCopy}
                                                    className="inline-flex items-center px-3 py-1.5 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors"
                                                >
                                                    <svg className="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
                                                    </svg>
                                                    {copySuccess ? '已复制' : '复制内容'}
                                                </button>
                                            </div>
                                        )}
                                    </div>
                                </div>
                                {isEditing ? (
                                    <div className="prose prose-indigo max-w-none">
                                        {isHtmlMode ? (
                                            <textarea
                                                ref={textareaRef}
                                                value={editContent}
                                                onChange={handleContentChange}
                                                className="w-full p-4 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                                                placeholder="请输入文章内容"
                                                style={{ overflow: 'hidden', resize: 'none' }}
                                            />
                                        ) : (
                                            <div
                                                ref={richEditorRef}
                                                contentEditable
                                                onInput={handleRichEditorChange}
                                                className="w-full p-4 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 min-h-[200px] overflow-auto"
                                                style={{ lineHeight: '1.5' }}
                                            />
                                        )}
                                    </div>
                                ) : (
                                    <div className="prose prose-indigo max-w-none">
                                        <style>
                                            {`
                                            .content-wrapper img {
                                                background-color: #f0f0f0;
                                                min-height: 100px;
                                                min-width: 100px;
                                                display: inline-block;
                                                border: 1px dashed #ccc;
                                            }
                                            .content-wrapper img.img-load-error {
                                                position: relative;
                                            }
                                            .content-wrapper img.img-load-error::after {
                                                content: "图片加载失败";
                                                position: absolute;
                                                top: 50%;
                                                left: 50%;
                                                transform: translate(-50%, -50%);
                                                color: #666;
                                                font-size: 12px;
                                            }
                                            `}
                                        </style>
                                        <div
                                            className="content-wrapper"
                                            dangerouslySetInnerHTML={{ __html: material ? processImageUrls(material.content) : '' }}
                                        ></div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                ) : null}

                {/* 保存确认弹窗 */}
                {showSaveConfirm && (
                    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50 animate-fadeIn">
                        <div className="bg-white w-full max-w-md mx-auto rounded-xl shadow-lg transform transition-all animate-scaleIn">
                            <div className="p-6">
                                <h3 className="text-lg font-medium text-gray-900 mb-4">确认保存</h3>
                                <p className="text-sm text-gray-500 mb-6">
                                    确定要保存编辑后的内容吗？此操作将会覆盖原有内容。
                                </p>
                                <div className="flex justify-end gap-3">
                                    <button
                                        onClick={() => setShowSaveConfirm(false)}
                                        className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
                                    >
                                        取消
                                    </button>
                                    <button
                                        onClick={handleSaveContent}
                                        className="px-4 py-2 bg-emerald-600 text-white rounded-lg text-sm font-medium hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 transition-colors"
                                    >
                                        确认保存
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {/* 提取话题确认弹窗 */}
                {showExtractConfirm && (
                    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50 animate-fadeIn">
                        <div className="bg-white w-full max-w-md mx-auto rounded-xl shadow-lg transform transition-all animate-scaleIn">
                            <div className="p-6">
                                <h3 className="text-lg font-medium text-gray-900 mb-4">确认重新提取</h3>
                                <p className="text-sm text-gray-500 mb-6">
                                    该素材已经提取过话题，确定要重新提取吗？
                                </p>
                                <div className="flex justify-end gap-3">
                                    <button
                                        onClick={() => setShowExtractConfirm(false)}
                                        className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
                                    >
                                        取消
                                    </button>
                                    <button
                                        onClick={doExtractTopic}
                                        className="px-4 py-2 bg-emerald-600 text-white rounded-lg text-sm font-medium hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 transition-colors"
                                    >
                                        确认提取
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {/* Toast提示 */}
                {toast.visible && (
                    <div className="fixed bottom-6 right-6 z-50 animate-scalein">
                        <div className={`rounded-lg shadow-lg py-3 px-4 flex items-center gap-2 ${toast.type === 'success' ? 'bg-emerald-500 text-white' :
                            toast.type === 'error' ? 'bg-rose-500 text-white' :
                                'bg-indigo-500 text-white'
                            }`}>
                            {toast.type === 'success' && (
                                <svg className="w-5 h-5" viewBox="0 0 20 20" fill="currentColor">
                                    <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                                </svg>
                            )}
                            {toast.type === 'error' && (
                                <svg className="w-5 h-5" viewBox="0 0 20 20" fill="currentColor">
                                    <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                                </svg>
                            )}
                            {toast.type === 'info' && (
                                <svg className="w-5 h-5" viewBox="0 0 20 20" fill="currentColor">
                                    <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2h-1V9z" clipRule="evenodd" />
                                </svg>
                            )}
                            <span className="font-medium">{toast.message}</span>
                        </div>
                    </div>
                )}
            </main>
        </div>
    );
};

export default MaterialDetail; 